package com.hiray.demos.android_features

import android.app.KeyguardManager
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.IBinder
import android.os.PowerManager
import android.view.WindowManager

class ScreenWallpaperService : Service() {

    private val WAKETAG = "WakeLockTAG"
    private lateinit var keyguardManager: KeyguardManager
    private lateinit var screenReceiver: ScreenStateReceiver

    override fun onCreate() {
        keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
        val lock = keyguardManager.newKeyguardLock("KeyguardLock")
        lock.disableKeyguard()
        screenReceiver = ScreenStateReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF)
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT)
        registerReceiver(screenReceiver, intentFilter)
    }

    inner class ScreenStateReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            if (intent.action == Intent.ACTION_SCREEN_OFF) {
                val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
                val wakeLock = powerManager.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WAKETAG)
                wakeLock.acquire(1200)
                val intenter = Intent(this@ScreenWallpaperService, ScreenWallPaperActivity::class.java)
                startActivity(intenter)
                wakeLock.release()
            } else if (intent.action == Intent.ACTION_SCREEN_ON) {

            }
        }

    }


    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(screenReceiver)
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

}